package com.example.geoaimavlink_android.activity.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.MAVLink.enums.MAV_TYPE
import com.example.geoaimavlink_android.R
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.ProductManager
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.StarLinkClientManager
import com.geoai.module.common.thread.ExecutorsManager
import kotlinx.android.synthetic.main.frag_mult_connection.btnConnectionSelect
import kotlinx.android.synthetic.main.frag_mult_connection.btnLand
import kotlinx.android.synthetic.main.frag_mult_connection.btnTakeOff
import kotlinx.android.synthetic.main.frag_mult_connection.spConnectionSelect
import kotlinx.android.synthetic.main.frag_mult_connection.tvConnectionSN
import kotlinx.android.synthetic.main.frag_mult_connection.tvConnectionSelected
import kotlinx.android.synthetic.main.frag_mult_connection.tvDroneConnectCount
import kotlinx.android.synthetic.main.frag_mult_connection.tvFcStatus
import kotlin.math.pow
import kotlin.math.sqrt

/**
 * @Author      : Ronny
 * @Email       : Ronny_xie@hotmail.com
 * @Date        : on 2024-06-20 16:05.
 * @Description :
 */
class MultConnectionFragment : BaseFragment() {

    private var mCurrentSelectDroneIndex = -1

    private var mProductManager: ProductManager? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.frag_mult_connection, container, false)
    }

    override fun onStart() {
        super.onStart()
        // 开启无人机连接监听
        startDroneConnectionListener()
        // 初始化下拉框
        initSpinner()
        // 选择无人机
        btnConnectionSelect.setOnClickListener {
            mProductManager?.flyControllerManager?.setFlyControllerStateListener(null)
            tvFcStatus?.text = ""

            mCurrentSelectDroneIndex = spConnectionSelect.selectedItemPosition + 1

            val product = StarLinkClientManager.getInstance().getProduct(mCurrentSelectDroneIndex)

            if (product == null) {
                showToast("无法找到对应的无人机")
            } else if (!product.isConnected) {
                showToast("无人机不在线")
            } else {
                mProductManager = product

                mProductManager?.flyControllerManager?.setFlyControllerStateListener {
                    // 无人机状态监听
                    val sb = StringBuilder()

                    sb.append("lat: ${it.aircraftLatitude}").append("\r\n")
                    sb.append("lon: ${it.aircraftLongitude}").append("\r\n")
                    sb.append("alt: ${it.aircraftAltitude}").append("\r\n")
                    sb.append("vs: ${sqrt(it.aircraftVelocityX.toDouble().pow(2.0) + it.aircraftVelocityY.toDouble().pow(2.0))}").append("\r\n")
                    sb.append("zs: ${it.aircraftVelocityZ}").append("\r\n")
                    sb.append("satellites: ${it.aircraftGpsSatelliteNumber}").append("\r\n")
                    sb.append("yaw: ${it.aircraftYaw}").append("\r\n")
                    sb.append("pitch: ${it.aircraftPitch}").append("\r\n")
                    sb.append("roll: ${it.aircraftRoll}").append("\r\n")
                    sb.append("mode: ${it.flyMode.name}").append("\r\n")

                    tvFcStatus?.text = sb.toString()
                }
            }
        }
        btnTakeOff?.setOnClickListener {
            mProductManager?.flyControllerManager?.startAircraftTakeoff(20.0f, null)
        }
        btnLand?.setOnClickListener {
            mProductManager?.flyControllerManager?.startForceLanding(null)
        }
    }

    private fun initSpinner() {
        val upDownRatioArray = arrayOfNulls<String>(10)
        for ((index, s) in upDownRatioArray.withIndex()) {
            upDownRatioArray[index] = (index + 1).toString()
        }

        val spinnerAdapter: ArrayAdapter<String> = ArrayAdapter<String>(requireContext(), R.layout.item_select, upDownRatioArray)
        spConnectionSelect?.adapter = spinnerAdapter
    }

    private fun startDroneConnectionListener() {
        ExecutorsManager.get().let { executorsManager ->
            executorsManager.executeAtFixedRate({
                val count = StarLinkClientManager.getInstance().productManager.count()
                executorsManager.runOnMainThread {
                    tvConnectionSelected?.text = "当前选择的无人机ID：${mCurrentSelectDroneIndex}"
                    tvDroneConnectCount?.text = count.toString()
//                    tvConnectionSN?.text = buildDroneConnectionSN()
                }
            }, 1000, 2000)
        }
    }

//    private fun buildDroneConnectionSN(): String {
//        val sb = StringBuilder()
//
//        StarLinkClientManager.getInstance().productManager.forEach { sysID, productManager ->
//            val productSnInfo = ProductInfoManager.getInstance().getProductSnInfo(sysID, MAV_TYPE.MAV_TYPE_QUADROTOR.toShort())
//            sb.append("sysID: $sysID").append("\t  ")
//            sb.append("connected: ${productManager.isConnected}").append("\t  ")
//            sb.append("droneSn: $productSnInfo").append("\t  ")
//            sb.append("\r\n")
//        }
//
//        return sb.toString()
//    }
}